<template>
  <div class="permission">
    <el-card>
      <div class="add">
        <el-button @click="openAdd(1, '0')" type="primary" size="mini">
          <i class="el-icon-edit"></i>添加菜单
        </el-button>
      </div>
      <el-table :data="list" row-key="id">
        <el-table-column prop="name" label="菜单名称"> </el-table-column>
        <el-table-column prop="code" label="权限标识"> </el-table-column>
        <el-table-column prop="description" label="描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="openAdd(2, scope.row.id)" v-if="scope.row.type === 1" type="text">添加权限点</el-button>
            <el-button type="text">查看api权限</el-button>
            <el-button type="text" @click="openEdit(scope.row.id)">查看</el-button>
            <el-button @click="delPer(scope.row.id)" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <myPanel :panelShow.sync="panelShow" ref="mypanel" @updateData="getAllPer"></myPanel>
  </div>
</template>

<script>
import { getAllPerApi, delPerApi } from '@/api/permission'
export default {
  data() {
    return {
      // 权限列表
      list: [],
      // 查看面板
      panelShow: false
    }
  },
  methods: {
    // 打开新增面板
    openAdd(type, pid) {
      this.panelShow = true
      this.$refs.mypanel.getData(type, pid)
    },
    // 打开查看面板
    openEdit(id) {
      this.panelShow = true
      this.$refs.mypanel.getPerObj(id)
    },
    // 删除
    delPer(id) {
      this.$confirm('是否删除当前权限点', '提示')
        .then(async () => {
          await delPerApi(id)
          this.$message.success('删除成功')
          this.getAllPer()
        })
        .catch(() => {})
    },
    // 获取权限列表
    async getAllPer() {
      const res = await getAllPerApi()
      // console.log(res)
      this.list = this.trunData(res.data.data, '0')
    },
    // 转化为带子结构
    trunData(arr, pid) {
      const res = []
      arr.forEach(item => {
        if (item.pid === pid) {
          const children = this.trunData(arr, item.id)
          item.children = children
          res.push(item)
        }
      })
      return res
    }
  },
  created() {
    this.getAllPer()
  },
  components: {
    myPanel: () => import('./components/panel.vue')
  }
}
</script>

<style lang="scss">
.permission {
  margin: 20px;
  .add {
    text-align: right;
  }
}
</style>
